package controllers

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"

	"code.sgfoot.com/sg-seehome/common"
	"code.sgfoot.com/sg-seehome/models"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

//实现登陆 和 自动注册
func (this *AdminController) Login() {
	//显示页面
	if this.Ctx.Request.Method == "GET" {
		this.Data["title"] = "登陆入口"
		this.Data["page_type"] = "login"
		this.TplName = "login.tpl"
		return
	}
	//实例对象
	var obj models.Users
	mobile := this.GetString("mobile")
	password := this.GetString("password")
	if mobile == "" {
		this.SetJson(10, "手机号不能为空")
		return
	}
	b := this.o.QueryTable(new(models.Users)).Filter("mobile", mobile).Exist()
	if !b {
		obj.Mobile = mobile
		obj.Password = password
		err := obj.Insert()
		if err == nil {
			this.setLoginSession(obj)
			this.SetJson(0, "注册成功", "/")
			return
		} else {
			this.SetJson(1, "注册失败")
			return
		}
	}
	result, err := obj.SelectOne(mobile, password)
	if err == orm.ErrNoRows {
		this.SetJson(2, "密码错误")
		return
	}
	this.setLoginSession(result)
	this.SetJson(0, "登陆成功", "/")
	return
}

//添加基本信息
func (this *AdminController) HouseAdd() {
	if this.Ctx.Request.Method == "GET" {
		this.Data["title"] = "添加房屋信息"
		this.Data["floor_num"] = common.RangeNumber(25)
		id := this.GetString("id")
		idInt, _ := strconv.Atoi(id)
		var (
			minFloor, maxFloor int
			score, owner       string
		)
		if idInt > 0 {
			var row models.House
			err := this.o.QueryTable(new(models.House)).Filter("id", id).One(&row)
			if err == nil {
				fmt.Println(row.Json)
				var js models.HouseJson
				json.Unmarshal([]byte(row.Json), &js)
				floorArr := strings.Split(js.Floor, "/")
				minFloor, _ = strconv.Atoi(floorArr[0])
				maxFloor, _ = strconv.Atoi(floorArr[1])
				score = js.Score
				owner = js.Owner
				this.Data["row"] = js
			}
		}
		this.Data["id"] = id
		this.Data["minFloor"] = minFloor
		this.Data["maxFloor"] = maxFloor
		this.Data["null"] = ""
		this.Data["scoreList"] = models.GetScoreList()
		this.Data["score"] = score
		this.Data["ownerList"] = models.GetOwnerList()
		this.Data["owner"] = owner
		this.TplName = "house_add.tpl"
		return
	}
	id, _ := this.GetInt("id", 0)
	name := this.GetString("name")
	floor, _ := this.GetInt("floor")
	maxFloor, _ := this.GetInt("max_floor")
	amount, _ := this.GetInt("amount")
	score := this.GetString("score")
	owner := this.GetString("owner")
	mobile := this.GetString("mobile")
	address := this.GetString("address")
	remark := this.GetString("remark")
	if name == "" || floor <= 0 || amount <= 0 || owner == "" {
		this.SetJson(10, "参数异常")
		return
	}

	var houseJson models.HouseJson
	houseJson.Name = name
	houseJson.Floor = strconv.Itoa(floor) + "/" + strconv.Itoa(maxFloor)
	houseJson.Amount = amount
	houseJson.Owner = owner
	houseJson.Mobile = mobile
	houseJson.Address = address
	houseJson.Score = score
	houseJson.Remark = remark

	info, _ := json.Marshal(houseJson)
	var houseDb models.House
	userId := this.GetSession("user_id").(int)
	houseDb.UserId = userId
	houseDb.Json = string(info)
	fmt.Println("id:", id)
	if id > 0 {
		num, err := this.o.QueryTable(new(models.House)).Filter("user_id", userId).Filter("id", id).Update(orm.Params{
			"json":       info,
			"updated_at": common.GetNowDateTime(),
		})
		if err != nil {
			this.SetJson(22, err.Error())
			return
		}
		if num > 0 {
			this.SetJson(0, "更新成功,影响行"+strconv.FormatInt(num, 10))
		}
	} else {
		err := houseDb.Insert()
		if err != nil {
			this.SetJson(11, err.Error())
			return
		}
		this.SetJson(0, "添加成功")
	}
	this.SetJson(10, "操作失败")
	return
}

//显示房屋列表,处理
func (this *AdminController) HouseList() {
	if this.Ctx.Request.Method == "GET" {
		this.Data["title"] = "房屋列表"
		this.TplName = "house_list.tpl"
		return
	}
	userId := this.GetSession("user_id").(int)
	result, err := new(models.House).Select(userId)
	if err != nil {
		this.SetJsonLayui(21, err.Error(), 0, nil)
		return
	}
	data := make([]models.HouseJson, 0)
	for _, item := range result {
		child := models.HouseJson{}
		fmt.Println(item.Json)
		err = json.Unmarshal([]byte(item.Json), &child)
		if err != nil {
			this.SetJsonLayui(22, err.Error(), 0, nil)
			break
		}
		child.Id = item.Id
		child.TotalScore = new(models.Score).GetTotalScore(item.UserId, item.Id)
		child.CreatedAt = item.CreatedAt
		data = append(data, child)
	}
	count, err := this.o.QueryTable(new(models.House)).Filter("user_id", userId).Count()
	if err != nil {
		this.SetJsonLayui(23, err.Error(), 0, nil)
		return
	}
	this.SetJsonLayui(0, "", int(count), data)
	return
}

//删除房屋信息
func (this *AdminController) HouseDel() {
	id, _ := this.GetInt("id", 0)
	if id <= 0 {
		this.SetJson(1, "id不能为空")
		return
	}
	userId := this.GetSession("user_id").(int)
	this.o.QueryTable(new(models.House)).Filter("user_id", userId).Filter("id", id).Update(orm.Params{
		"state": "1",
	})
	this.SetJson(0, "删除成功")
}

//添加类型
func (this *AdminController) AddClassify() {
	if this.Ctx.Request.Method == "GET" {
		var classObj models.Classify
		rs, err := classObj.SelectParent()
		if err != nil {
			beego.Error("查询数据异常", err.Error())
		}
		this.Data["title"] = "添加类别信息"
		this.Data["Parent_list"] = rs
		this.TplName = "classify.tpl"
		return
	}
	typeName := this.GetString("type_name")
	parentId := this.GetString("parent_id")
	if typeName == "" || parentId == "" {
		res := common.SetJson(10, "参数错误", "")
		this.Data["json"] = &res
		this.ServeJSON()
		return
	}
	_parentId, _ := strconv.Atoi(parentId)
	userId := this.GetSession("user_id").(int)
	isAdmin := this.GetSession("is_admin").(int)
	var classObj models.Classify
	classObj.ParentId = _parentId
	classObj.TypeName = typeName
	//判断是否是管理员,若是则为公用类型
	if isAdmin == 0 {
		classObj.UserId = userId
	}
	//查检是否重名
	check := classObj.CheckName()
	if check {
		this.SetJson(10, "重名,请更改", "")
		return
	}
	err := classObj.Insert()
	if err != nil {
		this.SetJson(11, "参数错误", "")
		return
	} else {
		_map := make(map[string]string)
		_map["parent_id"] = strconv.Itoa(classObj.ParentId)
		_map["id"] = strconv.Itoa(classObj.Id)
		_map["name"] = classObj.TypeName
		this.SetJson(0, "添加成功", _map)
		return
	}
}

//获取子项
func (this *AdminController) GetClassifyChild() {
	parentId, _ := this.GetInt("id")
	if parentId == -1 {
		this.SetJson(10, "请选择", "")
		return
	}
	result, err := new(models.Classify).SelectChild(parentId)
	if err != nil {
		this.SetJson(11, err.Error(), "")
		return
	}
	type listS struct {
		Id   string `json:"id"`
		Name string `json:"name"`
	}
	var list []listS
	for _, item := range result {
		list = append(list, listS{
			Id:   item["id"].(string),
			Name: item["type_name"].(string),
		})
	}
	this.SetJson(0, "ok", list)
	return
}

//添加评分
func (this *AdminController) AddScore() {
	userId := this.GetSession("user_id").(int)
	houseId, _ := this.GetInt("house_id", 0)
	if this.Ctx.Request.Method == "GET" {
		this.Data["title"] = "添加综合积分"
		var classObj models.Classify
		ClassResult, err := classObj.Select(userId)
		if err != nil {
			beego.Error("查询数据异常", err.Error())
		}
		_map := make(map[interface{}]interface{})
		for _, item := range ClassResult {
			_parentId := item["parent_id"]
			if _parentId == "0" {
				_map[item["type_name"]] = item["id"]
			}
		}
		type info struct {
			Name  string
			Score int
		}
		//查询已设置的分
		var scoreList []models.Score
		this.o.QueryTable(new(models.Score)).Filter("user_id", userId).Filter("house_id", houseId).All(&scoreList)
		//构建类型ID 对应 分值
		scoreMap := make(map[int]int)
		for _, child := range scoreList {
			scoreMap[child.ClassifyId] = child.Score
		}
		//构建父子结构
		for name, parentId := range _map {
			child := make(map[interface{}]info)
			for _, item := range ClassResult {
				if parentId == item["parent_id"] {
					_score := 0
					if _s, ok := scoreMap[common.StringToInt(item["id"].(string))]; ok {
						_score = _s
					}
					child[item["id"]] = info{
						Name:  item["type_name"].(string),
						Score: _score,
					}
				}
			}
			_map[name] = child
		}
		this.Data["scoreLevel"] = models.GetScoreLevel()
		this.Data["Classify"] = _map
		this.Data["Parent_list"] = ClassResult
		this.Data["hid"] = houseId
		this.Data["null"] = ""
		this.TplName = "score.tpl"
	} else { //提交处理
		if houseId > 0 && userId > 0 {
			classIdArr := make([]int, 0)
			scoreArr := make([]int, 0)
			this.Ctx.Input.Bind(&classIdArr, "class_id")
			this.Ctx.Input.Bind(&scoreArr, "score")
			affectCount := 0
			for key, classId := range classIdArr {
				score := scoreArr[key]
				cnt, err := this.o.QueryTable(new(models.Score)).Filter("user_id", userId).Filter("classify_id", classId).Filter("house_id", houseId).Count()
				if err != nil {
					this.SetJson(11, err.Error())
					return
				}
				if cnt > 0 { //更新
					num, err := this.o.QueryTable(new(models.Score)).Filter("user_id", userId).Filter("classify_id", classId).Filter("house_id", houseId).Update(orm.Params{
						"score": score,
					})
					fmt.Println("num", num)
					if err != nil {
						this.SetJson(12, err.Error())
						return
					}
					if num >= 0 {
						affectCount++
					}
				} else { //新增
					sDb := models.Score{}
					sDb.UserId = userId
					sDb.HouseId = houseId
					sDb.ClassifyId = classId
					sDb.Score = score
					sDb.CreatedAt = common.GetNowDateTime()
					sDb.UpdatedAt = common.GetNowDateTime()
					num, err := this.o.Insert(&sDb)
					if err != nil {
						this.SetJson(12, err.Error())
						return
					}
					if num > 0 {
						affectCount++
					}
				}
			}
			if affectCount > 0 {
				this.SetJson(0, "操作成功")
				return
			}
		}
		this.SetJson(0, "操作失败")
		return
	}
}

//退出系统
func (this *AdminController) Logout() {
	this.DelSession("user_id")
	this.DelSession("mobile")
	this.DestroySession()
	this.History("退出", "/login")
}
